<template>
  <div class="mapbox" ref="mapDom"></div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, watch, toRaw, shallowRef } from 'vue'
import { useRouter } from 'vue-router'
import AMapLoader from '@amap/amap-jsapi-loader'

import imgUrl20 from '@/assets/img/20.png'
import imgUrl21 from '@/assets/img/21.png'
import led1 from '@/assets/img/led1.gif'
import led2 from '@/assets/img/led2.gif'

window._AMapSecurityConfig = {
  securityJsCode: 'ef549878a39bfe8a923b03e6df01ef2e'
}

const mapDom = ref(null)
const map = shallowRef(null)
const router = useRouter()

const props = defineProps({
  markList: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['markerClick'])

const addMapMarker = (paramMap, markerList = [], markIcon) => {
  // 添加地图标记
  const wIcon = new paramMap.Icon({
    // 图标尺寸
    size: new AMap.Size(40, 40),
    // 图标的取图地址
    image: imgUrl20,
    // 图标所用图片大小
    imageSize: new AMap.Size(40, 40)
  })
  const wIcon2 = new AMap.Icon({
    // 图标尺寸
    size: new AMap.Size(40, 40),
    // 图标的取图地址
    image: imgUrl21,
    // 图标所用图片大小
    imageSize: new AMap.Size(40, 40)
  })
  let _markerList = []
  for (let i = 0; i < markerList.length; i++) {
    _markerList[i] = new paramMap.Marker({
      position: new paramMap.LngLat(
        Number(markerList[i].longitude),
        Number(markerList[i].latitude)
      ),
      cursor: 'pointer',
      offset: new AMap.Pixel(-10, -10),
      icon: wIcon,
      extData: markerList[i]
    })
    map.value.add(_markerList[i])

    // 消息内容
    const createInfoWindow = (param) => {
      return `<div class="infor-box">
        <div class="infor-title">${param.landName}</div>
        <div class="infor-row">
            <div class="infor-item">
              <div class="infor-item-label">作物品种：</div>
              <div class="infor-item-value">${param.cropCount || 0}</div>
            </div>
            <div class="infor-item">
              <div class="infor-item-label">大棚数量：</div>
              <div class="infor-item-label">${param.houseCount || 0}</div>
            </div>
        </div>
        <div class="infor-row marginTop15">
            <div class="infor-item">
              <div class="infor-item-label">设备数量：</div>
              <div class="infor-item-label">${param.deviceCount || 0}</div>
            </div>
            <div class="infor-item">
              <div class="infor-item-label">地块面积：</div>
              <div class="infor-item-label">${param.landArea || 0}㎡</div>
            </div>
        </div>
        <div class="infor-btn" data-gopage="xcsj" data-id=${
          param.id
        }>现场概览数据</div>
      </div>`
    }
    // 创建消息窗体
    const infoWindow = new AMap.InfoWindow({
      isCustom: true, //使用自定义窗体
      // content: createInfoWindow({
      //   title: '大棚1'
      // }),
      offset: new AMap.Pixel(0, -10)
    })
    // 给每一个marker绑定点击事件
    _markerList[i].on('click', (e) => {
      const target = e.target
      const obj = target.getExtData()
      emit('markerClick', obj)
      map.value.clearInfoWindow()
      infoWindow.setContent(createInfoWindow(obj))
      infoWindow.open(map.value, _markerList[i].getPosition())
      e.target.setIcon(wIcon2)
      setTimeout(() => {
        map.value.setZoomAndCenter(11, e.target.getPosition())
        for (let j = 0; j < _markerList.length; j++) {
          if (i !== j) {
            _markerList[j].setIcon(wIcon)
          }
        }
      }, 800)
    })
  }
  // 点击地图，清楚marker的选中icon,并清除信息窗体
  map.value.on('click', (e) => {
    for (let j = 0; j < _markerList.length; j++) {
      _markerList[j].setIcon(wIcon)
    }
    map.value.clearInfoWindow() // 清除之前的标记
  })
}
const initMap = (markData) => {
  // 初始化地图
  AMapLoader.load({
    key: 'ef8c8773f0a70ebb0d5916b2c15d1504', //申请好的 Web 端开发者 Key，首次调用 load 时必填
    version: '2.0' //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
  })
    .then((AMap) => {
      // 中心点
      let centerPoint = [116.397428, 39.90923]
      if (markData[0] && markData[0].longitude) {
        // 第一个mark为中心点
        centerPoint = [
          Number(markData[0].longitude),
          Number(markData[0].latitude)
        ]
      }

      map.value = new AMap.Map(mapDom.value, {
        layers: [
          //使用多个图层
          new AMap.TileLayer.Satellite(),
          new AMap.TileLayer.RoadNet()
        ],
        center: centerPoint,
        zoom: 14,
        doubleClickZoom: false
      })
      addMapMarker(AMap, markData)
    })
    .catch((e) => {
      console.log(e)
    })
}

onMounted(() => {
  document.addEventListener('click', (e) => {
    const target = e.target
    if (target) {
      const mm = target.getAttribute('data-gopage')
      if (mm === 'xcsj') {
        const id = target.getAttribute('data-id')
        router.push({ path: '/greenhouse', query: { id } })
      }
    }
    e.stopPropagation()
  })
})

onUnmounted(() => {
  document.removeEventListener('click', (e) => {})
})

watch(
  () => props.markList,
  (newProps) => {
    const _markList = toRaw(newProps)
    // 是否存在地图实例，没有初始化
    if (map.value) {
      initMap(_markList)
    } else {
      initMap(_markList)
    }
  },
  { deep: true, immediate: true }
)
</script>

<style lang="scss" scoped>
.mapbox {
  width: 100%;
  height: 100%;
}
</style>
